//
//  TypeViewController.m
//  NewBook
//
//  Created by dlios on 15-3-7.
//  Copyright (c) 2015年 dlios. All rights reserved.
//

#import "TypeViewController.h"

@interface TypeViewController ()
@property (nonatomic, retain) NSMutableArray * dataArray;
@property (nonatomic) int rowValue;
@end

@implementation TypeViewController

-(void)dealloc
{
    [_buttonArray release];
    [_myTableView release];
    [_selectionList release];
    [_typeButtonArray release];
    [_selectedItemLabel release];
    [_artVC release];
    [_allYoungArray release];
    [super dealloc];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    //初始化数组
    self.dataArray = [[NSMutableArray alloc]init];

    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    //数组初始化
    self.allYoungArray = [NSMutableArray array];
    self.navigationItem.title = @"青春文学";

//    //初始化一个数组,用来存放图书分类的内容
//    self.buttonArray = [NSArray arrayWithObjects:@"青春文学", @"小说", @"文学", @"艺术", @"生活", @"管理", @"社科", @"科普", nil];
//   // NSLog(@"数组=%@", self.buttonArray);
//    UIScrollView *typeScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
//    typeScrollView.backgroundColor = [UIColor yellowColor];
//    //设置滚屏大小为两个屏幕宽度
//    typeScrollView.contentSize = CGSizeMake(self.view.frame.size.width * 2, 0);
//    //隐藏滚动条
//    //typeScrollView.showsHorizontalScrollIndicator = NO;
//    //设置边界是否反弹
//    typeScrollView.bounces = NO;
//    [self.view addSubview:typeScrollView];
//    
//    //循环创建分类按钮
//    for (int i = 0; i < 8; i++) {
//        UIButton *typeButton = [UIButton buttonWithType:UIButtonTypeCustom];
//        //为button设置tag值,方便后来的点击按钮触发的方法
//        typeButton.tag = 1001 + i;
//       // [typeButton setImage:[UIImage imageNamed:@"btn_popup_n@2x.png"] forState:UIControlStateNormal];
//        [typeButton setBackgroundImage:[UIImage imageNamed:@"btn_popup_n@2x.png"] forState:UIControlStateNormal];
//        //[typeButton setImage:[UIImage imageNamed:@"btn_popup-data_n@2x.png"] forState:UIControlStateHighlighted];
//        //从按钮数组中取出每个按钮的标题
//        NSString *buttonTitle = [self.buttonArray objectAtIndex:i];
//        [typeButton setTitle:buttonTitle forState:UIControlStateNormal];
//        typeButton.frame = CGRectMake(i * 95, 5, 90, 30);
//        [typeScrollView addSubview:typeButton];
//    }
//
    //---------------------------------------------------------
    //边界是否延展
    self.edgesForExtendedLayout = UIRectEdgeNone;
    //创建滚动屏列表
    self.selectionList = [[HTHorizontalSelectionList alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
    
    self.selectionList.delegate = self;
    self.selectionList.dataSource = self;
    //给类型按钮数组赋值
    self.typeButtonArray = @[@"青春文学",
                      @"小说",
                      @"文学",
                      @"艺术",
                      @"生活",
                      @"管理",
                      @"社科",
                      @"科普"];
    
    [self.view addSubview:self.selectionList];
    //创建滚屏上文字的lable
    self.selectedItemLabel = [[UILabel alloc] init];
    //给每个lable赋值,从typeButtonArray数组中足以取值
    self.selectedItemLabel.text = self.typeButtonArray[self.selectionList.selectedButtonIndex];
    self.selectedItemLabel.translatesAutoresizingMaskIntoConstraints = NO;
    [self.view addSubview:self.selectedItemLabel];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.selectedItemLabel
                                                          attribute:NSLayoutAttributeCenterX
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeCenterX
                                                         multiplier:1.0
                                                           constant:0.0]];
    
    [self.view addConstraint:[NSLayoutConstraint constraintWithItem:self.selectedItemLabel
                                                          attribute:NSLayoutAttributeCenterY
                                                          relatedBy:NSLayoutRelationEqual
                                                             toItem:self.view
                                                          attribute:NSLayoutAttributeCenterY
                                                         multiplier:1.0
                                                           constant:0.0]];

    
    
    
    
    
    //创建tableView,用来显示
    self.myTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height - 64 - 49 - 40) style:UITableViewStylePlain];
    //self.myTableView.rowHeight = 183;
    //把tableView的分割线去掉
    self.myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.myTableView.delegate = self;
    self.myTableView.dataSource = self;
    
    [self.view addSubview:self.myTableView];
     [_myTableView release];

    //首先创建对象,不能在点击方法时创建
    //艺术--------------------------------------------
    self.artVC = [[ArtViewController alloc] init];
    //添加到当前容器视图控制器下
    [self addChildViewController:self.artVC];
    [self.view addSubview:self.artVC.view];
    //先隐藏对象
    self.artVC.view.hidden = YES;
    //生活----------------------------------------------
    self.lifeVC = [[LifeViewController alloc] init];
    //添加到当前容器视图控制器下
    [self addChildViewController:self.lifeVC];
    [self.view addSubview:self.lifeVC.view];
    self.lifeVC.view.hidden = YES;
    //文学----------------------------------------------
    self.literatureVC = [[LiteratureViewController alloc] init];
    //添加到当前容器视图控制器下
    [self addChildViewController:self.literatureVC];
    [self.view addSubview:self.literatureVC.view];
    self.literatureVC.view.hidden = YES;

    //管理----------------------------------------------
    self.managerVC = [[ManagerViewController alloc] init];
    //添加到当前容器视图控制器下
    [self addChildViewController:self.managerVC];
    [self.view addSubview:self.managerVC.view];
    self.managerVC.view.hidden = YES;

    //小说----------------------------------------------
    self.novelVC = [[NovelViewController alloc] init];
    //添加到当前容器视图控制器下
    [self addChildViewController:self.novelVC];
    [self.view addSubview:self.novelVC.view];
    self.novelVC.view.hidden = YES;

    //社科----------------------------------------------
    self.socialVC = [[SocialViewController alloc] init];
    //添加到当前容器视图控制器下
    [self addChildViewController:self.socialVC];
    [self.view addSubview:self.socialVC.view];
    self.socialVC.view.hidden = YES;
    //科普----------------------------------------------
    self.scienceVC = [[ScienceViewController alloc] init];
    //添加到当前容器视图控制器下
    [self addChildViewController:self.scienceVC];
    [self.view addSubview:self.scienceVC.view];
    self.scienceVC.view.hidden = YES;


    [self addHeader];
    [self addFooter];
}

//下拉刷新
- (void)addHeader
{
    //NSLog(@"下拉刷新");
    __block TypeViewController *movieVC = self;
    [self.myTableView addHeaderWithCallback:^{
        //NSLog(@"222");
        movieVC.isUpLoading = NO;
        [self GetMovieList:0];
    }];
    [self.myTableView headerBeginRefreshing];
}
//上拉加载
- (void)addFooter
{
    //NSLog(@"上拉刷新");
    __block TypeViewController *movieVC = self;
    [self.myTableView addFooterWithCallback:^{
        //NSLog(@"333");
        movieVC.isUpLoading = YES;
        [movieVC GetMovieList:movieVC.page];
        
    }];
}

//AFN请求数据
- (void)GetMovieList:(NSInteger)page
{
    
    __block TypeViewController *root = self;
    
    NSString *url_string = [NSString stringWithFormat:@"http://mapi.dangdang.com/index.php?action=list_category&user_client=iphone&client_version=5.0.1&page=%ld&page_size=10&sort_type=default_0&cid=01.01.00.00.00.00&img_size=h&udid=18948B21919333DDC1DDE273A67E5005&time_code=407B1DF79FB9AE61C33B6B9B427E136D&timestamp=1425611964&union_id=537-50&permanent_id=20150304193014100686115327268485015",page + 1];
    
    AFNetworkReachabilityManager *netWorkManager = [AFNetworkReachabilityManager sharedManager];
    
    //****参数cursor的值: 第一页默认为0，下一页就是请求下来数据中next_cursor的值
    //****参数count 的值: 是指定一页显示多少条数据
    
    AFHTTPRequestOperationManager* manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/plain",@"text/json",@"application/json",@"text/javascript",@"text/html",nil];
    [manager GET:url_string parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [netWorkManager stopMonitoring];
        
        NSMutableDictionary *youngDic = responseObject;
        //记录下一页
        //先取出saleDic字典下的page字典
        NSMutableDictionary *pageDic = [youngDic objectForKey:@"page"];
        //然后取出pageDic字典下对应的pageindex内容
        self.page = [[pageDic objectForKey:@"pageindex"] integerValue];
        
        if (self.isUpLoading == NO) {
            //说明是下拉刷新，就要清空数组中的数据，保持数组中存放的是最新的数据
            [self.allYoungArray removeAllObjects];
            [self.dataArray removeAllObjects];
        }
        
        NSMutableArray *youngArray = [youngDic objectForKey:@"products"];
        NSInteger g = self.allYoungArray.count;
        for (NSMutableDictionary *dic in youngArray) {
            
            YoungBook *youngBook = [[YoungBook alloc] init];
            [youngBook setValuesForKeysWithDictionary:dic];
            youngBook.productId = [dic objectForKey:@"id"];

           //把对象添加进数组中
            [root.allYoungArray addObject:youngBook];
            [youngBook release];
        }
        //创建字典,设置默认的点击事件是关闭的
        NSDictionary *dic = @{@"Cell": @"MainCell",@"isAttached":@(NO)};
        //循环,
        for (NSInteger i = g ; i<root.allYoungArray.count; i++) {
            [self.dataArray addObject:dic];
        }
        //NSLog(@"%d,%d",self.dataArray.count,self.allYoungArray.count);
       
        [self.myTableView footerEndRefreshing];//结束底部刷新效果
        [self.myTableView headerEndRefreshing];//结束头部刷新效果
        [self.myTableView reloadData];//刷新tableview
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        NSLog(@"失败==== %@",error);
        
    }];
    
    
}


//滚动屏上item的数量
- (NSInteger)numberOfItemsInSelectionList:(HTHorizontalSelectionList *)selectionList {
    //返回所有类型数组的个数
    return self.typeButtonArray.count;
}
//滚动屏上的文字
- (NSString *)selectionList:(HTHorizontalSelectionList *)selectionList titleForItemWithIndex:(NSInteger)index {
    return self.typeButtonArray[index];
}

//点击item时触发的方法
- (void)selectionList:(HTHorizontalSelectionList *)selectionList didSelectButtonWithIndex:(NSInteger)index {
    // update the view for the corresponding index
    self.selectedItemLabel.text = self.typeButtonArray[index];
    NSLog(@"%ld", index);
    //如果点击的十青春文学的按钮
    if (index == 0) {
        
        //隐藏其他页面
        self.navigationItem.title = @"青春文学";
        self.novelVC.view.hidden = YES;
        self.literatureVC.view.hidden = YES;
        self.artVC.view.hidden = YES;
        self.lifeVC.view.hidden = YES;
        self.managerVC.view.hidden = YES;
        self.socialVC.view.hidden = YES;
        self.scienceVC.view.hidden = YES;
        //self.view.hidden = YES;
    }

    if (index == 1) {
        
   //  [self.view bringSubviewToFront:self.artVC.view];
        //隐藏其他页面
        self.navigationItem.title = @"小  说";
        self.novelVC.view.hidden = NO;
        self.literatureVC.view.hidden = YES;
        self.artVC.view.hidden = YES;
        self.lifeVC.view.hidden = YES;
        self.managerVC.view.hidden = YES;
        self.socialVC.view.hidden = YES;
        self.scienceVC.view.hidden = YES;
        //self.view.hidden = YES;
    }
    if (index == 2) {
        self.navigationItem.title = @"文  学";
        self.literatureVC.view.hidden = NO;
        //隐藏其他页面
        self.novelVC.view.hidden = YES;
        self.artVC.view.hidden = YES;
        self.lifeVC.view.hidden = YES;
        self.managerVC.view.hidden = YES;
        self.socialVC.view.hidden = YES;
        self.scienceVC.view.hidden = YES;
    }
    if (index == 3) {
        self.navigationItem.title = @"艺  术";
        self.artVC.view.hidden = NO;
        //隐藏其他页面
        self.literatureVC.view.hidden = YES;
        self.novelVC.view.hidden = YES;
        //self.artVC.view.hidden = YES;
        self.lifeVC.view.hidden = YES;
        self.managerVC.view.hidden = YES;
        self.socialVC.view.hidden = YES;
        self.scienceVC.view.hidden = YES;

    }
    if (index == 4) {
        self.navigationItem.title = @"生  活";
        self.lifeVC.view.hidden = NO;
        //隐藏其他页面
        self.literatureVC.view.hidden = YES;
        self.novelVC.view.hidden = YES;
        self.artVC.view.hidden = YES;
        //self.lifeVC.view.hidden = YES;
        self.managerVC.view.hidden = YES;
        self.socialVC.view.hidden = YES;
        self.scienceVC.view.hidden = YES;
    }

    if (index == 5) {
        self.navigationItem.title = @"管  理";
        self.managerVC.view.hidden = NO;
        //隐藏其他页面
        self.literatureVC.view.hidden = YES;
        self.novelVC.view.hidden = YES;
        self.artVC.view.hidden = YES;
        self.lifeVC.view.hidden = YES;
        //self.managerVC.view.hidden = YES;
        self.socialVC.view.hidden = YES;
        self.scienceVC.view.hidden = YES;
    }

    if (index == 6) {
        self.navigationItem.title = @"社  科";
        self.socialVC.view.hidden = NO;
        //隐藏其他页面
        self.literatureVC.view.hidden = YES;
        self.novelVC.view.hidden = YES;
        self.artVC.view.hidden = YES;
        self.lifeVC.view.hidden = YES;
        self.managerVC.view.hidden = YES;
        //self.socialVC.view.hidden = YES;
        self.scienceVC.view.hidden = YES;
    }
    if (index == 7) {
        self.navigationItem.title = @"科  普";
        self.scienceVC.view.hidden = NO;
        //隐藏其他页面
        self.literatureVC.view.hidden = YES;
        self.novelVC.view.hidden = YES;
        self.artVC.view.hidden = YES;
        self.lifeVC.view.hidden = YES;
        self.managerVC.view.hidden = YES;
        self.socialVC.view.hidden = YES;
        //self.scienceVC.view.hidden = YES;
    }



}
//设置tableview上section的个数
//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
//{
//    return 1;
//}


//tableview返回行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}
//tableview上cell的内容
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if ([[self.dataArray[indexPath.row] objectForKey:@"Cell"] isEqualToString:@"MainCell"])
    {
     static NSString *CellIdentifier = @"MainCell";
    TypeTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[TypeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
    }
    //将cell设置成点击时不变色
    cell.selectionStyle = UITableViewCellSelectionStyleNone;

        cell.youngBook = [self.allYoungArray objectAtIndex:indexPath.row];

  return cell;
    }
    else if([[self.dataArray[indexPath.row] objectForKey:@"Cell"] isEqualToString:@"AttachedCell"]){
        
        static NSString *CellIdentifier = @"AttachedCell";
        
        AttachedYoungTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        
        
        if (cell == nil) {
            cell = [[AttachedYoungTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
            
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            
            
            //将button设为属性,点击按钮触发的方法
            [cell.detailButton addTarget:self action:@selector(detailButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell.shareButton addTarget:self action:@selector(shareButtonAction:) forControlEvents:UIControlEventTouchUpInside];
            [cell.collectionButton addTarget:self action:@selector(collectionButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        return cell;
        
    }
    return nil;
}

//点击cell跳转页面方法

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    NSIndexPath * path = nil;
    if ([[self.dataArray[indexPath.row] objectForKey:@"Cell"] isEqualToString:@"MainCell"]) {
        path = [NSIndexPath indexPathForItem:(indexPath.row+1) inSection:indexPath.section];

    }else{
        path = indexPath;
    }


    //当点击大的cell时,把当前点击的大的cell上的对象取出来
    BookSale *bookSale = [self.allYoungArray objectAtIndex:indexPath.row];
    
    //创建AttachedYoungTableViewCell的对象
    self.attachedYoungCell = [[AttachedYoungTableViewCell alloc] init];
    //把当前的对象传给attachedYoungCell下的对象
    self.attachedYoungCell.bookSale = bookSale;
    
    //self.attachedYoungCell.indexx = indexPath.row;
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    

    
    if ([[self.dataArray[indexPath.row] objectForKey:@"isAttached"] boolValue]) {
        // 关闭附加cell
        NSDictionary * dic = @{@"Cell": @"MainCell",@"isAttached":@(NO)};
        self.dataArray[(path.row-1)] = dic;
        [self.dataArray removeObjectAtIndex:path.row];
        [self.allYoungArray removeObjectAtIndex:self.rowValue];
        
        [self.myTableView beginUpdates];
        [self.myTableView deleteRowsAtIndexPaths:@[path]  withRowAnimation:UITableViewRowAnimationMiddle];
        [self.myTableView endUpdates];
        
    }else{
       
       
        
        // 打开附加cell

        NSDictionary * dic = @{@"Cell": @"MainCell",@"isAttached":@(YES)};
        self.dataArray[(path.row-1)] = dic;
        NSDictionary * addDic = @{@"Cell": @"AttachedCell",@"isAttached":@(YES)};
        [self.dataArray insertObject:addDic atIndex:path.row];
        YoungBook * young = [[YoungBook alloc]init];
        [self.allYoungArray insertObject:young atIndex:path.row];
        self.rowValue = path.row;
        [self.myTableView beginUpdates];
        [self.myTableView insertRowsAtIndexPaths:@[path] withRowAnimation:UITableViewRowAnimationMiddle];
        [self.myTableView endUpdates];
    }
}
//设置tableview的cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //判断,如果是主cell,返回100
    if ([[self.dataArray[indexPath.row] objectForKey:@"Cell"] isEqualToString:@"MainCell"])
    {
        return 100;
    }else{
        //否则返回40
        return 40;
    }
    return 0;
}

//点击小的cell详情按钮触发的方法
-(void)detailButtonAction:(UIButton *)button
{
    //创建bookDetailsVC的对象
    BookDetailsViewController *bookDetailsVC = [[BookDetailsViewController alloc]init];
    //将self.attachedYoungCell.bookSale对象下的属性分别赋值给详情页面的属性
        bookDetailsVC.title = self.attachedYoungCell.bookSale.name;
        bookDetailsVC.nameStr = self.attachedYoungCell.bookSale.name;
        bookDetailsVC.authornameStr = self.attachedYoungCell.bookSale.authorname;
        bookDetailsVC.subNameStr = self.attachedYoungCell.bookSale.subname;
        bookDetailsVC.priceStr = [NSString stringWithFormat:@"￥ :    %@",self.attachedYoungCell.bookSale.dd_sale_price];
        bookDetailsVC.detailsImageStr = self.attachedYoungCell.bookSale.image_url;
    bookDetailsVC.productId = self.attachedYoungCell.bookSale.productId;
    
    //跳到详情页面
     [self.navigationController pushViewController:bookDetailsVC animated:YES];
    [bookDetailsVC release];
}
//点击小的cell上的分享按钮触发的方法
- (void)shareButtonAction:(UIButton *)button
{
    [UMSocialSnsService presentSnsIconSheetView:self
                                         appKey:@"507fcab25270157b37000010"
                                      shareText:@"你要分享的文字"
                                     shareImage:[UIImage imageNamed:@"icon.png"]
                                shareToSnsNames:[NSArray arrayWithObjects:UMShareToSina,UMShareToTencent,UMShareToRenren, UMShareToQzone, nil]
                                       delegate:self];

}
//点击小的cell上的收藏按钮触发的方法
- (void)collectionButtonAction:(UIButton *)button
{
    
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
